package com.bwstudio.demo.consumer.controller;

import java.util.concurrent.CompletableFuture;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bwstudio.demo.provider.api.OtherService;

import lombok.extern.slf4j.Slf4j;

/**
 * 这两个api在容器层面还是同步的，即用的时servlet的线程
 * @author buwei
 *
 */
@Slf4j
@RestController
public class TestDubboController {

	@Reference
	OtherService otherService;

	@GetMapping("/sync-dubbo-service")
	public void syncDo() {
		long startTime = System.currentTimeMillis();
		otherService.doFirst();
		otherService.doSecond();
		long syncInvokeuseTime = System.currentTimeMillis() - startTime;
		log.info("两个同步调用共计用时（毫秒）：" + syncInvokeuseTime);
//		return helloService.hello("Hello World!");
	}
	
	@GetMapping("/async-dubbo-service")
	public void asyncDo() {
		long startTime = System.currentTimeMillis();

		// 异步调用
		CompletableFuture<String> doThirdFuture = otherService.doThird();
		CompletableFuture<String> doFourthFuture = otherService.doFourth();

		long asyncInvokeuseTime = System.currentTimeMillis() - startTime;
		log.info("两个异步调用共计用时（毫秒）：" + asyncInvokeuseTime);

		doThirdFuture.whenComplete((result, throwable) -> {
			if (throwable != null) {
				throwable.printStackTrace();
			} else {
				log.info("异步调用提供者的doThird()返回值：" + result);
			}
		});

		doFourthFuture.whenComplete((result, throwable) -> {
			if (throwable != null) {
				throwable.printStackTrace();
			} else {
				log.info("异步调用提供者的doFourth()返回值：" + result);
			}
		});

		long getResultTime = System.currentTimeMillis() - startTime;
		log.info("两个异步调用返回结果共计用时（毫秒）：" + getResultTime);
	}
}
